package xyz.shu.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import xyz.shu.util.JsonMapper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * 拦截器
 * @author shujinhao
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
    private static final String START_TIME="requestStartTime";
    /**
     * 请求之前
     * @param request 请求
     * @param response 响应
     * @param handler 处理
     * @return 结果
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url=request.getRequestURI().toString();
        Map map = request.getParameterMap();
        log.info("request start url:{},params:{}",url,JsonMapper.obj2String(map));

        long start=System.currentTimeMillis();
        request.setAttribute(START_TIME,start);
        return true;
    }

    /**
     * 请求结束之后处理
     * @param request 请求
     * @param response 响应
     * @param handler 处理
     * @param modelAndView 结果
     * @throws Exception 异常
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        /*String url=request.getRequestURI().toString();
        long start=(Long) request.getAttribute(START_TIME);
        long end =System.currentTimeMillis();

        log.info("request finished url:{},cost:{}",url,end-start);*/
    }

    /**
     * 请求结束之后处理，异常情况也会调用
     * @param request 请求
     * @param response 响应
     * @param handler 处理
     * @param ex 异常结果
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        String url=request.getRequestURI().toString();
        long start=(Long) request.getAttribute(START_TIME);
        long end =System.currentTimeMillis();

        log.info("request complete url:{},cost:{}",url,end-start);
    }
}
